<script setup>
import {reactive, ref} from "vue";
  import axios from "axios";
  import {ElMessage, ElMessageBox} from "element-plus";
  import zhCn from "element-plus/es/locale/lang/zh-cn";

  const rules = reactive({
    customerId: [
      { required: true, message: '客户Id不能为空', trigger: 'blur' },
    ],
    productId:[
      { required: true, message: '产品Id不能为空', trigger: 'blur' },
    ],
    policyType:[
      { required: true, message: '保单类型不能为空', trigger: 'blur' },
    ],
    startDate:[
      { required: true, message: '开始时间不能为空', trigger: 'blur' },
       { validator: dateValidator, trigger: 'blur'}
    ],
    endDate:[
      { required: true, message: '结束时间不能为空', trigger: 'blur' },
       { validator: dateValidator, trigger: 'blur'}
    ],
    premium:[
      { required: true, message: '保费不能为空', trigger: 'blur' },
    ],
    status:[
      { required: true, message: '保费不能为空', trigger: 'blur' },
    ]
  })

  const pageConfig = reactive({ //页面配置对象
    dialogFormVisible:false, //dialogForm是否可见
    policyDialogData:{//dialogForm数据
      policyId:"",
      productId:"",
      customerId:"",
      policyType:"",
      startDate:"",
      endDate:"",
      premium:"",
      status:"",
      productName:"",
      customerName:"",
    },
    policyExtraData:{
      row:"",
    },
    customerNameFlag:"success",//控制dialog中的customerName颜色
    productNameFlag:"success",//控制dialog中的productName颜色
    statusFlag:"success",//控制dialog中的status颜色
    dialogStatus:false//true表示添加  false 表示修改
  })

  const formElRef = ref(null) //表单验证检测时的ref

  const tableData = reactive({//表格数据
    policyArr:[{
      policyId:"1",
      productId:"1",
      productName:"",
      customerId:"1",
      customerName:"",
      policyType:"人生保险",
      startDate:"2024-1-1",
      endDate:"2025-1-1",
      premium:"10000",
      status:"在保"
    }],
    likeCustomerName:"",
    likeProductName:"",
    likePolicyType:"",
    pageSize:5,//一页数据条数
    pageNum:1,//当前所在页数
    total:100,//总页数
    pages:1,
    policyType:[
      "个人",
      "商业"
    ],
    statusType:[
        "在保",
        "过保",
        "待开始"
    ]
  })

  load()

  /* 表格数据加载函数 */
  function load(){
    axios({
      url:"http://localhost:8080/boot/policy/findAllPolicyByPage",
      method:"get",
      params:{
        likePolicyType:tableData.likePolicyType,
        likeProductName:tableData.likeProductName,
        likeCustomerName:tableData.likeCustomerName,
        pageSize:tableData.pageSize,
        pageNum:tableData.pageNum
      }
    }).then((result)=>{
      tableData.policyArr = result.data.list
      tableData.pageNum = result.data.pageNum
      tableData.pageSize = result.data.pageSize
      tableData.total = result.data.total
      tableData.pages = result.data.pages
    })

  }

  /* dialog关闭时触发函数 */
  function handleClose(){//dialog关闭时执行
    pageConfig.dialogFormVisible=false
    pageConfig.policyDialogData={}
  }

  /* dialog保存按钮触发函数 */
  function persistence(){//dialog执行控制函数
    formElRef.value.validate((valid) => {
      if (valid) {
        console.log("表单验证成功")
        if(pageConfig.dialogStatus === false){
          update()
        }else if(pageConfig.dialogStatus === true){
          add()
        }
      } else {
        console.log('表单验证失败')
      }
    })

  }

  /* 将dialog变成添加状态 */
  function changeAdd(){
    pageConfig.dialogStatus=true//设置dialogStatus为添加状态
    pageConfig.dialogFormVisible=true
  }

  /* 编辑某行 */
  function handleEdit(row,index){
    pageConfig.dialogStatus=false//设置dialogStatus为修改状态
    pageConfig.policyDialogData.policyId=row.policyId
    pageConfig.policyDialogData.productId=row.productId
    pageConfig.policyDialogData.customerId=row.customerId
    pageConfig.policyDialogData.policyType=row.policyType
    pageConfig.policyDialogData.startDate=row.startDate
    pageConfig.policyDialogData.endDate=row.endDate
    pageConfig.policyDialogData.premium=row.premium
    pageConfig.policyDialogData.status=row.status

    //不能直接修改的
    pageConfig.policyDialogData.productName=row.productName
    pageConfig.policyDialogData.customerName=row.customerName

    //行数
    pageConfig.policyExtraData.row=index

    pageConfig.dialogFormVisible=true
  }

  /* 异步插入请求函数 */
  function add(){
    axios({
      url:"http://localhost:8080/boot/policy/insertPolicy",
      params:pageConfig.policyDialogData
    }).then((result)=>{
      if(result.data==="插入成功"){
        ElMessage({
          type:"success",
          message:result.data
        })
      }else{
        ElMessage({
          type:"error",
          message:"插入失败，未知错误"
        })
      }

      load()
      handleClose()
    })
  }
  /* 更新 */
  function update(){
    axios({
      url:"http://localhost:8080/boot/policy/updatePolicy",
      params:pageConfig.policyDialogData
    }).then((result)=>{
      if(result.data==="更新成功"){
        ElMessage({
          type:"success",
          message:result.data
        })
      }else{
        ElMessage({
          type:"error",
          message:"更新失败，未知错误"
        })
      }

      load()
      handleClose()
    })
  }
  /* 删除 */
  function handleDelete(row){
    ElMessageBox.confirm(
        '是否确认删除！！！！！！！！！',
        '删除确认',
        {
          confirmButtonText: '确认删除',
          cancelButtonText: '取消删除',
          type: 'warning',
        }
    ).then(() => {
      //发起删除请求
      axios({
        url:"http://localhost:8080/boot/policy/deleteByPolicyId",
        params:row
      }).then((result)=>{
        if(result.data.data==="删除成功"){
          ElMessage({
            type:"warning",
            message:"删除成功"
          })
        }else{
          ElMessage({
            type:"error",
            message:result.data.msg
          })
        }
        load()
      })
    }).catch(() => {
      //取消删除
      ElMessage({
        type: 'info',
        message: '已取消删除',
      })
    })
  }

  /* page分页中页大小改变时，触发的函数 */
  function handleSizeChange(){
    load()
  }

  /* page分页中当前页号改变时，触发的函数 */
  function handleCurrentChange(){
    load()
  }

  /* 查找客户姓名 */
  function findCustomName(){
    axios({
      url:"http://localhost:8080/boot/customer/findCustomerByCustomerId",
      params:{
        customerId:pageConfig.policyDialogData.customerId
      }
    }).then((result)=>{
      if(result.data.customerName!=="未找到"){
        pageConfig.customerNameFlag="success"
        pageConfig.policyDialogData.customerName =result.data.customerName
        ElMessage({
          type:"success",
          message:"已找到该用户"
        })
      }else{
        pageConfig.customerNameFlag="danger"
        pageConfig.policyDialogData.customerName="该用户不存在"
        ElMessage({
          type:"error",
          message:"该用户不存在"
        })
      }
    })
  }

  /* 查找产品姓名 */
  function findProductName(){
    axios({
      url:"http://localhost:8080/boot/insProduct/findInsProductByInsProductId",
      params:{
        productId:pageConfig.policyDialogData.productId
      }
    }).then((result)=>{
      if(result.data.productName!=="未找到"){
        pageConfig.productNameFlag="success"
        pageConfig.policyDialogData.productName =result.data.productName
        ElMessage({
          type:"success",
          message:"已找到该产品"
        })
      }else{
        pageConfig.productNameFlag="danger"
        pageConfig.policyDialogData.productName="该产品不存在"
        ElMessage({
          type:"error",
          message:"该产品不存在"
        })
      }
    })
  }

  /* 保费金额计算 */
  function calculatePremium(){
    //产品id为空
    if(pageConfig.policyDialogData.productId === "" || pageConfig.policyDialogData.productId === undefined){
      ElMessage({
        type:"error",
        message:"产品ID未给出！！！"
      })
      return
    }
    //生效和失效时间为空
    if(pageConfig.policyDialogData.startDate === undefined || pageConfig.policyDialogData.startDate === ""
        || pageConfig.policyDialogData.endDate === undefined || pageConfig.policyDialogData.endDate === ""){
      if( startDate > endDate){
        ElMessage({
          type:"error",
          message:"保单持续时间错误"
        })
      }
      return
    }

    const startDate = new Date(pageConfig.policyDialogData.startDate);
    const endDate = new Date(pageConfig.policyDialogData.endDate);
    if( startDate > endDate){
      ElMessage({
        type:"error",
        message:"保单持续时间错误"
      })
      return
    }

    axios({
      url:"http://localhost:8080/boot/insProduct/findInsProductByInsProductId",
      params:{
        productId:pageConfig.policyDialogData.productId
      }
    }).then((result)=>{
      // 计算时间差（毫秒）
      const timeDiff = endDate - startDate;
      //转换为年数
      const yearsDiff = timeDiff /  (1000 * 60 * 60 * 24 * 365.25);

      //四舍五入
      let money = Math.round(yearsDiff * result.data.premium *100)/100

      //保留两位小数
      pageConfig.policyDialogData.premium = money.toFixed(2);
      ElMessage({
        type:"success",
        message:"保费计算成功"
      })
    })
  }

  /* 保单状态检测 */
  function checkStatus() {
    if (pageConfig.policyDialogData.startDate !== undefined && pageConfig.policyDialogData.startDate !== ""
        && pageConfig.policyDialogData.endDate !== undefined && pageConfig.policyDialogData.endDate !== "") {
      if (pageConfig.policyDialogData.startDate < pageConfig.policyDialogData.endDate) {
        const startDate = new Date(pageConfig.policyDialogData.startDate);
        const endDate = new Date(pageConfig.policyDialogData.endDate);
        let now = new Date()
        if(now < startDate){
          pageConfig.statusFlag = "info"
          pageConfig.policyDialogData.status="待开始"
        }else if(now > startDate && now < endDate){
          pageConfig.statusFlag = "success"
          pageConfig.policyDialogData.status="在保"
        }else if(now > endDate){
          pageConfig.statusFlag = "error"
          pageConfig.policyDialogData.status="已过期"
        }

        return
      }
    }
    ElMessage({
      type:"error",
      message:"保单持续时间错误"
    })
  }

  /* 保单截至时间校验规则函数 */
  function dateValidator(rule,value, callback){
    if(pageConfig.policyDialogData.startDate !== undefined && pageConfig.policyDialogData.startDate !== ""
        && pageConfig.policyDialogData.endDate !== undefined && pageConfig.policyDialogData.endDate !== ""){
      if(pageConfig.policyDialogData.startDate > pageConfig.policyDialogData.endDate){
        if(value === pageConfig.policyDialogData.endDate){
          callback(new Error("保单失效时间必须大于等于生效时间"))
        }else{
          callback(new Error("保单生效时间必须小于于等于失效时间"))
        }
      }else {
        callback()
      }
    }else
      callback()
  }

  function updatePolicyStatus(){
    axios({
      url:"http://localhost:8080/boot/policy/updatePolicyStatus"
    }).then((result)=>{
      ElMessage({
        type:"success",
        message:`更新了${result.data}条数据`
      })

      load()
    })
  }

</script>

<template>
  <h1 align="center">保 单 信 息</h1>
  <el-divider />

  <!--  添加/修改表单-->
  <el-dialog
      v-model="pageConfig.dialogFormVisible"
      :before-close="handleClose"
      :title="pageConfig.dialogStatus?'增加信息':'修改信息'"
      width="40%">
    <el-form
        ref="formElRef"
        :model="pageConfig.policyDialogData"
        label-width="auto"
        style="max-width: 500px;"
        :rules="rules">
<!--      <el-form-item label="保单ID" style="margin-left: 35px">-->
<!--        <el-input v-model="pageConfig.policyDialogData.policyId" autocomplete="off" />-->
<!--      </el-form-item>-->
      <el-form-item label="客户ID" style="margin-left: 35px" prop="customerId">
        <el-input v-model="pageConfig.policyDialogData.customerId" autocomplete="off"  @change="findCustomName()"/>
      </el-form-item>
      <el-form-item label="客户名" style="margin-left: 35px">
        <el-text   :type=pageConfig.customerNameFlag>{{pageConfig.policyDialogData.customerName}}</el-text>
      </el-form-item>
      <el-form-item label="产品ID" style="margin-left: 35px"  prop="productId">
        <el-input v-model="pageConfig.policyDialogData.productId" autocomplete="off" @change="findProductName()"/>
      </el-form-item>
      <el-form-item label="产品名" style="margin-left: 35px" >
        <el-text :type=pageConfig.productNameFlag>{{pageConfig.policyDialogData.productName}}</el-text>
      </el-form-item>
      <el-form-item label="保单类型" style="margin-left: 35px" prop="policyType">
        <el-select   v-model="pageConfig.policyDialogData.policyType" placeholder="请选择">
          <el-option v-for="type in tableData.policyType"
                     :key="type"
                     :value="type"
                     :label="type"
          >
            {{type}}
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="保单生效时间" style="margin-left: 35px" prop="startDate">
        <el-config-provider :locale="zhCn">
          <el-date-picker
              v-model="pageConfig.policyDialogData.startDate"
              type="date"
              placeholder="请选择日期"
              format="YYYY/MM/DD"
              value-format="YYYY-MM-DD"
          />
        </el-config-provider>
      </el-form-item>
      <el-form-item label="保单失效时间" style="margin-left: 35px" prop="endDate">
        <el-config-provider :locale="zhCn">
          <el-date-picker
              v-model="pageConfig.policyDialogData.endDate"
              type="date"
              placeholder="请选择日期"
              format="YYYY/MM/DD"
              value-format="YYYY-MM-DD"
          />
        </el-config-provider>
      </el-form-item>
      <el-form-item label="保费" style="margin-left: 35px" prop="premium">
        <el-text type="warning">{{pageConfig.policyDialogData.premium}}</el-text>
        <el-button type="primary" @click="calculatePremium()" style="margin-left: 30px">生成保费</el-button>
      </el-form-item>
      <el-form-item label="状态" style="margin-left: 35px" prop="status">
        <el-tag :type="pageConfig.statusFlag">{{pageConfig.policyDialogData.status}}</el-tag>
        <el-button type="success" @click="checkStatus" style="margin-left: 30px">状态检测</el-button>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" @click="persistence()">
          保存数据
        </el-button>
      </div>
    </template>
  </el-dialog>

  <!-- 模糊查询和新增操作 -->
  <el-form :inline="true" :model="tableData.customerArr" class="demo-form-inline">
    <el-form-item label="客户姓名">
      <el-input v-model="tableData.likeCustomerName" placeholder="模糊查询" clearable />
    </el-form-item>
    <el-form-item label="保险产品名">
      <el-input v-model="tableData.likeProductName" placeholder="模糊查询" clearable />
    </el-form-item>
    <el-form-item label="保单类型">
      <el-input v-model="tableData.likePolicyType" placeholder="模糊查询" clearable />
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="load()">查询</el-button>
    </el-form-item>
    <el-form-item>
      <el-button type="success" @click="changeAdd()">新增保单</el-button>
    </el-form-item>
    <el-form-item>
      <el-button type="warning" @click="updatePolicyStatus()">更新保单状态</el-button>
    </el-form-item>
  </el-form>

  <!--  保单信息表-->
  <el-table :data="tableData.policyArr" style="width: 100%">

    <el-table-column label="保单ID" width="60">
      <template #default="scope">
        <el-tag type="primary">{{scope.row.policyId}}</el-tag>
      </template>
    </el-table-column>

    <el-table-column label="保险产品ID" width="60">
      <template #default="scope">
        <el-tag type="success">{{scope.row.productId}}</el-tag>
      </template>
    </el-table-column>

    <el-table-column label="保险产品名" prop="productName" width="130" />

    <el-table-column label="客户ID" width="60">
      <template #default="scope">
        <el-tag type="warning">{{scope.row.customerId}}</el-tag>
      </template>
    </el-table-column>

    <el-table-column label="客户名" prop="customerName" width="70" />

    <el-table-column label="保单类型" prop="policyType" width="150" />

    <el-table-column label="开始时间" prop="startDate" width="130"/>

    <el-table-column label="结束时间" prop="endDate" width="130"/>

    <el-table-column label="保费" prop="premium" width="100"/>

    <el-table-column label="保单状态" prop="status" />

    <el-table-column label="操作" width="150" fixed="right">
      <template #default="scope" >
        <el-button
            size="small"
            type="warning"
            @click="handleEdit(scope.row,scope.$index)"
        >
          修改
        </el-button>
        <el-button
            size="small"
            type="danger"
            @click="handleDelete(scope.row)"
        >
          删除
        </el-button>
      </template>
    </el-table-column>

  </el-table>

  <el-row>
    <el-divider />
    <el-config-provider :locale="zhCn">
      <el-pagination
          v-model:current-page="tableData.pageNum"
          v-model:page-size="tableData.pageSize"
          :page-sizes="[2,5, 10, 20, 50]"
          :page-count="tableData.pages"
          :background="true"
          layout="total, sizes, prev, pager, next, jumper"
          :total="tableData.total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
      />
    </el-config-provider>
  </el-row>
</template>

<style scoped>

</style>